package com.usian.article.controller;

import com.usian.article.ApAuthorControllerApi;
import com.usian.article.service.impl.ApAuthorServiceImpl;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;


@RestController
@RequestMapping("/api/v1/author")
@MapperScan("com.usian.article.mapper")
public class ApAuthorController implements ApAuthorControllerApi {

    @Autowired
    private ApAuthorServiceImpl service;


    /**
     *根据用户id查询作者信息
     * @param id
     * @return
     */
    @Override
    @GetMapping("/findByUserId/{id}")
    public ApAuthor findByUserId(@PathVariable("id") Integer id) {
        return service.findByUserId(id);
    }

    /**
     *根据用户id查询作者信息
     * @param id
     * @return
     */
    @Override
    @GetMapping("/findById/{id}")
    public ApAuthor findById(@PathVariable("id") Integer id) {
        if (id == null){
            return null;
        }
        return service.getById(id);
    }

    @GetMapping("/findByName/{name}")
    public ApAuthor selectAuthorByName(@PathVariable("name") String name) {
        return service.selectAuthorByName(name);
    }

    /**
     * 保存作者
     * @param apAuthor
     * @return
     */
    @Override
    @PostMapping("/save")
    public ResponseResult save(@RequestBody ApAuthor apAuthor) {
        ApAuthor byUserId = findByUserId(apAuthor.getUserId());
        if (byUserId == null){
        apAuthor.setCreatedTime(new Date());
        boolean save = service.save(apAuthor);
        return save?service.okResult(apAuthor.getId()):ResponseResult.errorResult(AppHttpCodeEnum.SAVE_FAILED);
        }
        return service.okResult(byUserId.getId());
    }

}
